package middle;

import java.util.HashSet;
import java.util.Set;

public class Solution_36 {

    public boolean isValidSudoku(char[][] board) {
        Set<Integer>[] rows = new Set[9];
        Set<Integer>[] cols = new Set[9];
        Set<Integer>[][] sets = new Set[3][3];
        for (int i = 0; i < board.length; i++) {
            int r = i / 3;
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == '.') {
                    continue;
                }
                int num = board[i][j] - '0';
                // 九宫格
                int c = j / 3;
                Set<Integer> set = sets[r][c];
                if (set == null) {
                    set = new HashSet<>();
                }
                if (set.contains(num)) {
                    return false;
                }
                set.add(num);
                sets[r][c] = set;

                // 同行
                Set<Integer> row = rows[i];
                if (row == null) {
                    row = new HashSet<>();
                }
                if (row.contains(num)) {
                    return false;
                }
                row.add(num);
                rows[i] = row;

                // 同列
                Set<Integer> col = cols[j];
                if (col == null) {
                    col = new HashSet<>();
                }
                if (col.contains(num)) {
                    return false;
                }
                col.add(num);
                cols[j] = col;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Solution_36 model = new Solution_36();
        System.out.println(model.isValidSudoku(new char[][]
            {{'8','3','.','.','7','.','.','.','.'}
            ,{'6','.','.','1','9','5','.','.','.'}
            ,{'.','9','8','.','.','.','.','6','.'}
            ,{'8','.','.','.','6','.','.','.','3'}
            ,{'4','.','.','8','.','3','.','.','1'}
            ,{'7','.','.','.','2','.','.','.','6'}
            ,{'.','6','.','.','.','.','2','8','.'}
            ,{'.','.','.','4','1','9','.','.','5'}
            ,{'.','.','.','.','8','.','.','7','9'}}));
    }
}
